package huoye.shops.huoye.mine.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.codeideology.android.previewimage.PrevieImage;
import com.codeideology.android.previewimage.PrevieImageActivity;
import com.codeideology.android.utils.BarUtils;
import com.codeideology.android.utils.StringUtils;
import com.codeideology.android.widget.recycler.RecyclerViewAdapter;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import huoye.shops.R;
import huoye.shops.base.APIUrls;
import huoye.shops.base.BaseTakePhotoActivity;
import huoye.shops.base.UserManager;
import huoye.shops.common.AddPictureAdapter;
import huoye.shops.common.ImageTextAdapter;
import huoye.shops.common.model.OssImageData;
import huoye.shops.huoye.mine.model.ShopDetials;
import huoye.shops.huoye.mine.model.detialsImg;
import huoye.shops.huoye.mine.presenter.EditShopMessagePresenter;
import huoye.shops.huoye.mine.view.IEditShopMessageView;
import huoye.shops.huoye.operation.model.AddImage;
import huoye.shops.huoye.operation.model.Descript;
import huoye.shops.huoye.operation.model.DetialImgs;
import huoye.shops.huoye.operation.model.ShopCouponsList;
import huoye.shops.huoye.operation.model.ShopEventPrizeList;

public class EditShopMessageActivity extends BaseTakePhotoActivity implements IEditShopMessageView{

    @BindView(R.id.edit_shop_message_et_shop_name)
    EditText etShopName;
    @BindView(R.id.edit_shop_message_et_contact)
    EditText etContact;
    @BindView(R.id.edit_shop_message_et_tel)
    EditText etTel;

    @BindView(R.id.edit_shop_message_tv_map_message)
    EditText etMapMessage;



    @BindView(R.id.edit_shop_message_rv_shop_photo)
    RecyclerView rvShopPhoto;
    @BindView(R.id.edit_shop_message_rv_shop_details)
    RecyclerView rvShopDetails;
    private ShopDetials shopDetials;
    private EditShopMessagePresenter mEditShopMessagePresenter;


    @BindView(R.id.edit_shop_message_iv_add_pic_logo)
    ImageView ivAddPicLogo;
    @BindView(R.id.edit_shop_message_iv_del_pic_logo)
    ImageView ivDelPicLogo;
    private String userShopId;


    @OnClick(R.id.edit_shop_message_iv_add_pic_logo)
    void onAddPicLogoClick(){
        isClickShopLogo = true;
         isClickShopPhoto = false;
         takePhoto();
    }



    @OnClick(R.id.edit_shop_message_iv_del_pic_logo)
    void onDelPicLogoClick(){
        mEditShopMessagePresenter.deleteOssImg(logoImg);
    }



    private String shopName;
    private String contactName;
    private String contactTel;
    private String logoImg = "";
    private List<String> faceImg = new ArrayList<>();
    private String province;
    private  String city;
    private String area;
    private String address;



    @OnClick(R.id.edit_shop_message_btn_save_message)
    void onSaveMessageClick(){
        shopName = etShopName.getText().toString();
        contactName = etContact.getText().toString();
        contactTel = etTel.getText().toString();
        address = etMapMessage.getText().toString();


        List<AddImage> images = shopPhotoAdapter.getData();
        if(shopPhotoAdapter != null || images != null ||images.size() >1) {
            for (AddImage image : images) {
                if(StringUtils.isNotEmpty(image.getImageUrl())){
                    faceImg.add(image.getImageUrl());
                }
            }
        }

        List<Descript> data = imageTextAdapter.getData();
        if(imageTextAdapter != null || data != null ||data.size() >1) {
            for (int i = 0 ; i < data.size(); i++){
                if(StringUtils.isNotEmpty(data.get(i).getImaPath())){
                    data.get(i).setImgUrl(data.get(i).getImaPath()) ;
                }
            }
        }





        mEditShopMessagePresenter.editShopInfo(shopName,contactName,contactTel,
                                                  logoImg,faceImg,province,city,
                                                  area,address,data);
    }


    private AMapLocationClientOption mLocationOption = null;
    private AMapLocationClient mLocationClient = null;

    @OnClick(R.id.edit_shop_message_btn_location)
    void onLocationClick(){
        setLocation();
    }
    private void setLocation(){
        openPower();
        getCurrentLocationLatLng();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //可在此继续其他操作。
        getCurrentLocationLatLng();
    }


    //打开定位权限
    private void openPower(){
        if((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED)){
            //如果没有授权，则请求授权
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1311);
            //String数组中为申请的权限，第一个是相机，第二个为修改内存，最后的参数即为申请授权的返回值，我设置的1311
        }
    }





    private int shopPhotoMax = 6;
    private AddPictureAdapter shopPhotoAdapter;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_edit_shop_message;
    }




    @Override
    protected void initView(@Nullable Bundle bundle) {
        shopDetials = getIntentData();
        setTitle("编辑");
        initUI();
        mEditShopMessagePresenter = new EditShopMessagePresenter();
        mEditShopMessagePresenter.addTaskListener(this);
        mEditShopMessagePresenter.onStart();

        userShopId = UserManager.getInstance().getUserShopId();
        showShopDetailsAdapter();
        initializeRecyclerView();

    }

    private void initUI() {
        etShopName.setText(shopDetials.getShopName());
        etShopName.setSelection(shopDetials.getShopName().length());//将光标移至文字末尾
        etContact.setText(shopDetials.getContactName());
        etTel.setText(shopDetials.getContactTel());
        etMapMessage.setText(shopDetials.getCity()+shopDetials.getArea()+shopDetials.getAddress());

        province = shopDetials.getProvince();
        city = shopDetials.getCity();
        area = shopDetials.getArea();
        address = shopDetials.getAddress();
        logoImg = shopDetials.getShopLogo();
        if(StringUtils.isNotEmpty(logoImg)){
            Glide.with(this)
                    .load(APIUrls.COMMON_CONFIG.TYPE_COMMON_ALIYUN+logoImg)
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .placeholder(R.mipmap.ic_wait_logo)
                    .error(R.mipmap.ic_error)
                    .into(ivAddPicLogo);
            ivDelPicLogo.setVisibility(View.VISIBLE);
        }

    }



    /**
     *  初始化定位并设置定位回调监听
     */
    private void getCurrentLocationLatLng(){
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        // 同时使用网络定位和GPS定位,优先返回最高精度的定位结果,以及对应的地址描述信息
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
       //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。默认连续定位 切最低时间间隔为1000ms
        mLocationOption.setInterval(3500);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    private String location = "";

    /**
     * 定位回调监听器
     */
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
                if (amapLocation != null) {
                    if (amapLocation.getErrorCode() == 0) {
                        //定位成功回调信息，设置相关消息
                        amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                        double currentLat = amapLocation.getLatitude();//获取纬度
                        double currentLon = amapLocation.getLongitude();//获取经度
                   /*currentLatLng = new LatLng(currentLat, currentLon);*/   //latlng形式的
                        Log.i("currentLocation", "currentLat : " + currentLat + " currentLon : " + currentLon);
                        amapLocation.getAccuracy();//获取精度信息
                        location =  amapLocation.getCity()+amapLocation.getDistrict();
                        etMapMessage.setText(location);
                        etMapMessage.requestFocus();
                        etMapMessage.setSelection(etMapMessage.getText().length());

                        province = amapLocation.getProvince();
                        city = amapLocation.getCity();
                        area = amapLocation.getDistrict();


                        mLocationClient.stopLocation();//停止定位


                    } else {
                        //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError", "location Error, ErrCode:"
                                + amapLocation.getErrorCode() + ", errInfo:"
                                + amapLocation.getErrorInfo());
                    }
                }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mLocationClient!=null) {
            mLocationClient.onDestroy();//销毁定位客户端。
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(mLocationClient!=null) {
            mLocationClient.startLocation(); // 启动定位
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
        if(mLocationClient!=null) {
            mLocationClient.stopLocation();//停止定位
        }
    }


    private List<AddImage> AddImageList = new ArrayList<>();

    private void showShopDetailsAdapter() {
        shopPhotoAdapter = new AddPictureAdapter(this);
        List<detialsImg> faceImgs = shopDetials.getFaceImg();
        if(faceImgs.size() > 0){
            for (int i = 0 ;i < faceImgs.size();i++){
                AddImage addImage = new AddImage();
                addImage.setImageUrl(faceImgs.get(i).getImgUrl());
                addImage.setLocal(false);
                AddImageList.add(addImage);
            }
            shopPhotoAdapter.setData(AddImageList);
        }
        shopPhotoAdapter.setMaxCount(shopPhotoMax);
        shopPhotoAdapter.setOnItemClickListener(new AddPictureAdapter.OnItemClickListener<AddImage>() {
            @Override
            public void onItemClick(AddImage addImage, int position, View view) {
                int count = shopPhotoAdapter.getItemCount();
                if(shopPhotoAdapter.getListCount() == shopPhotoMax) {
                    if(position == shopPhotoMax - 1) {
                        return;
                    }
                } else {
                    if(position == count - 1) {
                        isClickShopLogo = false;
                        isClickShopPhoto = true;
                        takePhoto();
                        return;
                    }
                }
                List<PrevieImage> images = new ArrayList<>();
                List<AddImage> data = shopPhotoAdapter.getData();
                for (int i = 0; i < data.size() ; i++) {
                    PrevieImage image = new PrevieImage();
                    String url = APIUrls.COMMON_CONFIG.TYPE_COMMON_ALIYUN+data.get(i).getImageUrl();
                    image.setThumbnailUrl(url);
                    image.setImageViewWidth(view.getWidth());
                    image.setImageViewHeight(view.getHeight());
                    int[] points = new int[2];
                    view.getLocationInWindow(points);
                    image.setImageViewX(points[0]);
                    image.setImageViewY(points[1] - BarUtils.getStatusBarHeight(EditShopMessageActivity.this));
                    images.add(image);
                }
                PrevieImageActivity.onStartActivity(EditShopMessageActivity.this, (ArrayList<PrevieImage>) images, position);
            }
        });
        rvShopPhoto.setLayoutManager(new GridLayoutManager(this, 3));
        rvShopPhoto.setAdapter(shopPhotoAdapter);
    }




    //判断图文是否为空
    private boolean isNull(){
        List<Descript> list = imageTextAdapter.getData();
        for (int i = 0 ;i <list.size() ; i++){

            if(!StringUtils.isNotEmpty(list.get(i).getImgDes())){
                makeToast("请填写商店描述");
                return false;
            }

            if(!StringUtils.isNotEmpty(list.get(i).getImgUrl())){
                makeToast("请选择商店详情图片");
                return false;
            }

        }
        return true;
    }






    List<Descript> imageTextList = new ArrayList<>();
    private void initData(){
        if(shopDetials.getDetialsImg().size() == 0){
            for (int i = 0 ; i < 1 ;i++){
                imageTextList.add(new Descript());
            }
        }else {
            List<detialsImg> detialsImg = shopDetials.getDetialsImg();
            for (int i = 0; i < detialsImg.size() ; i++){
                Descript descript = new Descript();
                descript.setImgDes(detialsImg.get(i).getImgDes());
                descript.setImgUrl(detialsImg.get(i).getImgUrl());
                descript.setLocal(false);
                imageTextList.add(descript);
            }
        }
    }

    private void addData(){
        if(imageTextAdapter != null){
            imageTextAdapter.getData().add(new Descript());
            imageTextAdapter.notifyDataSetChanged();
        }
    }


    private boolean isClickShopLogo;
    private boolean isClickShopPhoto;

    private int mPosition;
    private int imageTextMax = 100;
    private ImageTextAdapter imageTextAdapter;

    private void initializeRecyclerView(){
        imageTextAdapter = new ImageTextAdapter(this);
        initData();
        imageTextAdapter.setData(imageTextList);
        imageTextAdapter.setMaxCount(imageTextMax);
        imageTextAdapter.setOnItemClickListener(new ImageTextAdapter.OnItemClickListener<Descript>() {
            @Override
            public void onItemClick(Descript list, int i, View view) {
                int count = imageTextAdapter.getItemCount();
                if (imageTextAdapter.getListCount() == imageTextMax) {
                    if (i == imageTextMax - 1) {
                        return;
                    }
                } else {
                    if (i == count - 1) {
                        boolean b = isNull();
                        if(b){
                            addData();
                        }
                        return;
                    }
                }
            }
            @Override
            public void onAddImageClick(int position) {
                isClickShopLogo = false;
                isClickShopPhoto = false;
                mPosition = position;
                takePhoto();
            }
        });
        rvShopDetails.setLayoutManager(new LinearLayoutManager(this));
        rvShopDetails.setAdapter(imageTextAdapter);

    }

    private String imgPath = "";
    private String imgPhotoPath = "";
    private String imgDescriptPath = "";
    @Override
    public void takeSuccess(TResult result) {
        if (result != null) {
            TImage image = result.getImage();
            //上传单张图片
            if(isClickShopLogo){
                imgPath = image.getCompressPath();
                File file = new File(imgPath);
                mEditShopMessagePresenter.uploadOssImg(userShopId,"shop",imgPath);
                Glide.with(this)
                        .load(Uri.fromFile(file))
                        .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                        .placeholder(R.mipmap.ic_wait_logo)
                        .error(R.mipmap.ic_error)
                        .into(ivAddPicLogo);
                ivDelPicLogo.setVisibility(View.VISIBLE);
            }else {
                if(isClickShopPhoto){
                    AddImage img = new AddImage();
                    imgPhotoPath = image.getCompressPath();
                    mEditShopMessagePresenter.uploadOssImg(userShopId,"shop",imgPhotoPath);
                    img.setPath(imgPhotoPath);
                    img.setLocal(true);
                    if(shopPhotoAdapter.getListCount() == 0) {
                        shopPhotoAdapter.add(0, img);
                    } else {
                        shopPhotoAdapter.add(shopPhotoAdapter.getListCount() , img);
                    }
                    shopPhotoAdapter.notifyDataSetChanged();
                }else {
                    imgDescriptPath = image.getCompressPath();
                     mEditShopMessagePresenter.uploadOssImg(userShopId,"shop",imgDescriptPath);
                    imageTextAdapter.getData().get(mPosition).setImgUrl(imgDescriptPath);
                    imageTextAdapter.getData().get(mPosition).setLocal(true);
                    imageTextAdapter.notifyDataSetChanged();
                }
            }



        }
    }





    @Override
    public void setUploadMore(List<OssImageData> ossImageData) {

    }


    @Override
    public void setUpload(OssImageData ossImageData) {

        if(isClickShopLogo){
            logoImg = ossImageData.getFilePath();
        }else {
            if(isClickShopPhoto){
                List<AddImage> images = shopPhotoAdapter.getData();
                if(shopPhotoAdapter == null || images == null ||images.size() < 1) {
                    return;
                }
                for (AddImage image : images) {
                    if(image.getPath().equals(imgPhotoPath)){
                        image.setImageUrl(ossImageData.getFilePath());
                    }
                }

            }else {

                List<Descript> images = imageTextAdapter.getData();
                if(imageTextAdapter == null || images == null ||images.size() < 1) {
                    return;
                }
                for (Descript image : images) {
                    if(image.getImgUrl().equals(imgDescriptPath)){
                        image.setImaPath(ossImageData.getFilePath());
                    }
                }

            }
        }



    }

    @Override
    public void setDelImage() {
        ivAddPicLogo.setImageResource(R.mipmap.ic_add_image);
        ivDelPicLogo.setVisibility(View.GONE);
    }


}
